/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "spi.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "ad9833.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
volatile uint32_t SetKeyTick=0;
volatile uint32_t KeyTick=0;
uint16_t SetKeyValue;
uint16_t SetKeyValueTmp;
uint16_t KeyValue;
uint16_t KeyValueTmp;
uint16_t LastSetKeyValue;
uint16_t LastKeyValue;
uint8_t FreqCount = 0;
uint8_t ToneCount = 0;
WaveDef WaveCount = 0;
uint8_t DitherFlag = 0; // 抖动
uint8_t DitherCount = 0;
float DitherCoefficient[8]={
  1.00,
  1.02,
  1.04,
  1.02,
  1.0,
  0.98,
  0.96,
  0.98,
  };
volatile uint32_t DitherTick=0;

GPIO_TypeDef*  KeyPortTab[20] = 
{
  Key1_GPIO_Port,
  Key2_GPIO_Port,
  Key3_GPIO_Port,
  Key4_GPIO_Port,
  Key5_GPIO_Port,
  Key6_GPIO_Port,
  Key7_GPIO_Port,
  Key8_GPIO_Port,
  Key9_GPIO_Port,
  Key10_GPIO_Port,
  Key11_GPIO_Port,
  Key12_GPIO_Port,
  Key13_GPIO_Port,
  Key14_GPIO_Port,
  Key15_GPIO_Port,
  Key16_GPIO_Port,
  Key17_GPIO_Port,
  Key18_GPIO_Port,
  Key19_GPIO_Port,
  Key20_GPIO_Port,
};

uint32_t KeyPinTab[20] =
{
  Key1_Pin,
  Key2_Pin,
  Key3_Pin,
  Key4_Pin,
  Key5_Pin,
  Key6_Pin,
  Key7_Pin,
  Key8_Pin,
  Key9_Pin,
  Key10_Pin,
  Key11_Pin,
  Key12_Pin,
  Key13_Pin,
  Key14_Pin,
  Key15_Pin,
  Key16_Pin,
  Key17_Pin,
  Key18_Pin,
  Key19_Pin,
  Key20_Pin,
};


uint16_t ToneTab[44] = {
  TONE_A2  , TONE_AS2 , TONE_B2
  , TONE_C3  , TONE_CS3 , TONE_D3  , TONE_DS3 , TONE_E3  , TONE_F3
  , TONE_FS3 , TONE_G3  , TONE_GS3 , TONE_A3  , TONE_AS3 , TONE_B3
  , TONE_C4  , TONE_CS4 , TONE_D4  , TONE_DS4 , TONE_E4  , TONE_F4
  , TONE_FS4 , TONE_G4  , TONE_GS4 , TONE_A4  , TONE_AS4 , TONE_B4
  , TONE_C5  , TONE_CS5 , TONE_D5  , TONE_DS5 , TONE_E5  , TONE_F5
  , TONE_FS5 , TONE_G5  , TONE_GS5 , TONE_A5  , TONE_AS5 , TONE_B5
  , TONE_C6  , TONE_CS6 , TONE_D6  , TONE_DS6 , TONE_E6
};
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */
  uint8_t i=0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_SPI1_Init();
  /* USER CODE BEGIN 2 */
  SetKeyTick = HAL_GetTick();
  KeyTick = HAL_GetTick();
  // AD9833_Init(wave_sine,0,0);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    if (HAL_GetTick() - SetKeyTick > 100)
    {
      SetKeyTick = HAL_GetTick();
      SetKeyValueTmp = SetKeyValue;
      
      SetKeyValue = 0x00;
      if (HAL_GPIO_ReadPin(KeyUp_GPIO_Port, KeyUp_Pin) == GPIO_PIN_RESET)
      {
        SetKeyValue = 0x01;
      }
      if (HAL_GPIO_ReadPin(KeyDown_GPIO_Port, KeyDown_Pin) == GPIO_PIN_RESET)
      {
        SetKeyValue |= 0x02;
      }
    }

    if (HAL_GetTick() - KeyTick > 5)
    {
      KeyTick = HAL_GetTick();
      KeyValueTmp = KeyValue;
      KeyValue = 0x00;
      for (i = 0; i < 20; i++)
      {
        if (HAL_GPIO_ReadPin(KeyPortTab[i], KeyPinTab[i]) == GPIO_PIN_RESET)
        {
          KeyValue = i + 1;
          break;
        }
      }
    }

    if(SetKeyValueTmp == SetKeyValue)
    {
      if ((LastSetKeyValue&0xF) != SetKeyValue)
      {
        LastSetKeyValue <<= 4;
        LastSetKeyValue |= SetKeyValue;
        switch (LastSetKeyValue & 0xFFF) // 抬手才处理
        {
        case 0x0010: // UP
          if (ToneCount < 2)
            ToneCount++;
          break;
        case 0x0020: // Down
          if (ToneCount > 0)
            ToneCount--;
          break;
        case 0x0030: // wave
          WaveCount++;
          if (WaveCount > 2)
            WaveCount = 0;
          AD9833_OutputEnable(0);
          AD9833_SetWaveform(WaveCount);
          break;
        case 0x0230://开关颤音
        case 0x0231:
        case 0x0232:
          DitherFlag = !DitherFlag;
          break;
        default:
          break;
        }
      }
    }
    
    if(KeyValueTmp == KeyValue)
    {
      if (LastKeyValue != KeyValue)
      {
        if(KeyValue==0)
        {
          // AD9833_OutputEnable(0);
          AD9833_SetFrequency(0);
        }
        else
        {
          if(LastKeyValue==0)
          {
            AD9833_OutputEnable(1);
          }
          FreqCount = (KeyValue-1)+ToneCount*12;
          DitherCount = 0;
          AD9833_SetFrequency(ToneTab[FreqCount]);
          DitherTick = HAL_GetTick();
        }
        LastKeyValue = KeyValue;
      }
      else
      {
        if((DitherFlag!=0)&&(KeyValue!=0))
        {
          if (HAL_GetTick() - DitherTick > 20)
          {
            DitherTick = HAL_GetTick();
            AD9833_SetFrequency(ToneTab[FreqCount]*DitherCoefficient[DitherCount]);
            DitherCount++;
            if(DitherCount>=8)
            {
              DitherCount = 0;
            }
          }
        }
      }
    }
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_4;
  RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
